<?php
require('SendSms.php');

session_start();
include_once("../../untils/conn.php");
mysqli_query($con, "set names utf8");

$goods = mysqli_real_escape_string($con, $_POST['goods']);
$name = mysqli_real_escape_string($con, $_POST['name']);
$uid = mysqli_real_escape_string($con, $_POST['uid']);
$phone = mysqli_real_escape_string($con, $_POST['phone']);
$sf = mysqli_real_escape_string($con, $_POST['sf']);
$city = mysqli_real_escape_string($con, $_POST['city']);
$xian = mysqli_real_escape_string($con, $_POST['xian']);
$dizhi = mysqli_real_escape_string($con, $_POST['dizhi']);
$oderid = mysqli_real_escape_string($con, $_POST['oderid']);
$time = mysqli_real_escape_string($con, $_POST['time']);
$price = mysqli_real_escape_string($con, $_POST['price']);
$proxy_id = mysqli_real_escape_string($con, $_POST['proxyid']);
$proxy_price = mysqli_real_escape_string($con, $_POST['proxy_prices']);
$api_type = mysqli_real_escape_string($con, $_POST['apiType']);
// 外加佣金参数
$beizhu = "订单号:" . $oderid . "返佣￥" . $proxy_price;
$beizhus = "已经提交运营商审核";

// 查询 proxy 表，根据 proxy_id 获取代理级别、proxy_upid 和 proxy_acc
$sql = "SELECT * FROM proxy WHERE proxy_id = '$proxy_id'";
$result = mysqli_query($con, $sql);
if ($result) {
  $row = mysqli_fetch_assoc($result);
  $group_id = $row['group_id'];
  $proxy_upid = $row['proxy_upid'];
  $proxy_acc = $row['proxy_acc'];

  // 查询 proxy_group 表，获取对应的 group_name 和 group_portion
  $group_name = "";
  $group_portion = 0;
  $sql = "SELECT * FROM proxy_group WHERE group_id = '$group_id'";
  $result = mysqli_query($con, $sql);
  if ($result) {
    $row = mysqli_fetch_assoc($result);
    $group_name = $row['group_name'];
    $group_portion = $row['group_portion'];
  }

  // 根据代理级别进行不同的查询
if ($group_name == '三级代理') {
    // 查询上级代理
    $sql = "SELECT * FROM proxy WHERE proxy_id = '$proxy_upid'";
    $result = mysqli_query($con, $sql);
    if ($result) {
        $row = mysqli_fetch_assoc($result);
        $proxy_upid_2 = $row['proxy_upid'];
        $proxy_acc_2 = $row['proxy_acc'];
        $group_id_2 = $row['group_id'];

        //取比例
        $sql_group_2 = "SELECT * FROM proxy_group WHERE group_id = '$group_id_2'";
        $result_group_2 = mysqli_query($con, $sql_group_2);
        if ($result_group_2) {
            $row_group_2 = mysqli_fetch_assoc($result_group_2);
            $group_portion_2 = $row_group_2['group_portion'];
        }
        $newprice_a = $proxy_price + $group_portion;
        $newprice_b = $proxy_price + $group_portion - $group_portion_2;
        $newprice_2 = $newprice_a - $newprice_b;
        // 查询上上级代理
        $sql = "SELECT * FROM proxy WHERE proxy_id = '$proxy_upid_2'";
        $result = mysqli_query($con, $sql);
        if ($result) {
            $row = mysqli_fetch_assoc($result);
            $proxy_acc_3 = $row['proxy_acc'];
            $group_id_3 = $row['group_id'];

            //取比例
            $sql_group_3 = "SELECT * FROM proxy_group WHERE group_id = '$group_id_3'";
            $result_group_3 = mysqli_query($con, $sql_group_3);
            if ($result_group_3) {
                $row_group_3 = mysqli_fetch_assoc($result_group_3);
                $group_portion_3 = $row_group_3['group_portion'];
            }
            $newprice_a = $proxy_price + $group_portion;
            $newprice_b = $proxy_price + $group_portion - $group_portion_3;
            $newprice_3 = $newprice_a - $newprice_b;

            // 判断是否有name，uid，phone，dizhi这四项信息，如果有任何一项为空，则返回错误信息
            if (empty($name) || empty($uid) || empty($phone) || empty($dizhi)) {
                $response = array('status' => -1, 'msg' => '信息不完整，请重新输入');
                echo json_encode($response);
                return;
            }
        
            // 判断订单是否已经提交过
            session_start();
            if (isset($_SESSION['order_id']) && $_SESSION['order_id'] == $oderid) {
                $response = array('status' => 1, 'msg' => '订单已经提交过了');
                echo json_encode($response);
                return;
            }

            $data_query = mysqli_query($con, "select * from oder where uid='$uid'");
            $count = mysqli_num_rows($data_query);
        
            if ($count > 10) {
                // 用户已经申请过了，返回状态码1和提示信息
                $response = array('status' => 1, 'msg' => '您申请的订单已超限，请联系客服');
                echo json_encode($response);
            } else {
                // 订单写入数据库成功后执行写入佣金表
                $data_insert = mysqli_query($con, "INSERT INTO oder(goods, name, uid, phone, sf, city, xian, dizhi, oderid, time, proxy_id, proxy_price, price, api_type) VALUES ('$goods', '$name', '$uid', '$phone', '$sf', '$city', '$xian', '$dizhi', '$oderid', '$time', '$proxy_id', '$proxy_price', '$price', '$api_type')");

                // 写入佣金表
                $data_revenue = mysqli_query($con, "INSERT INTO revenue(account, oderid, name, price, beizhu, cr_time, proxy_upid, proxy_prices, proxy_upids, proxy_pricess) VALUES ('$proxy_acc', '$oderid', '$name', '$proxy_price', '$beizhu', '$time', '$proxy_acc_2', '$newprice_2', '$proxy_acc_3',  '$newprice_3')");
            }
        }
    }
} elseif ($group_name == '二级代理') {
    // 查询上级代理
    $sql = "SELECT * FROM proxy WHERE proxy_id = '$proxy_upid'";
    $result = mysqli_query($con, $sql);
    if ($result) {
        $row = mysqli_fetch_assoc($result);
        $proxy_acc_2 = $row['proxy_acc'];
        $group_id_2 = $row['group_id'];

        //取比例
        $sql_group_2 = "SELECT * FROM proxy_group WHERE group_id = '$group_id_2'";
        $result_group_2 = mysqli_query($con, $sql_group_2);
        if ($result_group_2) {
            $row_group_2 = mysqli_fetch_assoc($result_group_2);
            $group_portion_2 = $row_group_2['group_portion'];
        }
        $newprice_a = $proxy_price + $group_portion;
        $newprice_b = $proxy_price + $group_portion - $group_portion_2;
        $newprice_2 = $newprice_a - $newprice_b;

         // 判断是否有name，uid，phone，dizhi这四项信息，如果有任何一项为空，则返回错误信息
            if (empty($name) || empty($uid) || empty($phone) || empty($dizhi)) {
                $response = array('status' => -1, 'msg' => '信息不完整，请重新输入');
                echo json_encode($response);
                return;
            }
        
            // 判断订单是否已经提交过
            session_start();
            if (isset($_SESSION['order_id']) && $_SESSION['order_id'] == $oderid) {
                $response = array('status' => 1, 'msg' => '订单已经提交过了');
                echo json_encode($response);
                return;
            }

            $data_query = mysqli_query($con, "select * from oder where uid='$uid'");
            $count = mysqli_num_rows($data_query);
        
            if ($count > 10) {
                // 用户已经申请过了，返回状态码1和提示信息
                $response = array('status' => 1, 'msg' => '您申请的订单已超限，请联系客服');
                echo json_encode($response);
        } else {
            // 订单写入数据库成功后执行写入佣金表
            $data_insert = mysqli_query($con, "INSERT INTO oder(goods, name, uid, phone, sf, city, xian, dizhi, oderid, time, proxy_id, proxy_price, price ,api_type) VALUES ('$goods', '$name', '$uid', '$phone', '$sf', '$city', '$xian', '$dizhi', '$oderid', '$time', '$proxy_id', '$proxy_price', '$price', '$api_type')");

            // 写入佣金表
            $data_revenue = mysqli_query($con, "INSERT INTO revenue(account, oderid, name, price, beizhu, cr_time, proxy_upid, proxy_prices) VALUES ('$proxy_acc', '$oderid', '$name', '$proxy_price', '$beizhu', '$time', '$proxy_acc_2', '$newprice_2')");
        }
     }
  }elseif ($group_name == '一级代理') {
     // 判断是否有name，uid，phone，dizhi这四项信息，如果有任何一项为空，则返回错误信息
    if (empty($name) || empty($uid) || empty($phone) || empty($dizhi)) {
        $response = array('status' => -1, 'msg' => '信息不完整，请重新输入');
        echo json_encode($response);
        return;
    }

    // 判断订单是否已经提交过
    session_start();
    if (isset($_SESSION['order_id']) && $_SESSION['order_id'] == $oderid) {
        $response = array('status' => 1, 'msg' => '订单已经提交过了');
        echo json_encode($response);
        return;
    }

    $data_query = mysqli_query($con, "select * from oder where uid='$uid'");
    $count = mysqli_num_rows($data_query);

    if ($count > 10) {
        // 用户已经申请过了，返回状态码1和提示信息
        $response = array('status' => 1, 'msg' => '您申请的订单已超限，请联系客服');
        echo json_encode($response);
    } else {
        // 订单写入数据库成功后执行写入佣金表
        $data_insert = mysqli_query($con, "INSERT INTO oder(goods, name, uid, phone, sf, city, xian, dizhi, oderid, time, proxy_id, proxy_price, price ,api_type) VALUES ('$goods', '$name', '$uid', '$phone', '$sf', '$city', '$xian', '$dizhi', '$oderid', '$time', '$proxy_id', '$proxy_price', '$price' , '$api_type')");

        // 写入佣金表
        $data_revenue = mysqli_query($con, "INSERT INTO revenue(account, oderid, name, price, beizhu, cr_time) VALUES ('$proxy_acc', '$oderid', '$name', '$proxy_price', '$beizhu', '$time')");
    }
} elseif ($group_name == '运营平台') {
     // 判断是否有name，uid，phone，dizhi这四项信息，如果有任何一项为空，则返回错误信息
    if (empty($name) || empty($uid) || empty($phone) || empty($dizhi)) {
        $response = array('status' => -1, 'msg' => '信息不完整，请重新输入');
        echo json_encode($response);
        return;
    }

    // 判断订单是否已经提交过
    session_start();
    if (isset($_SESSION['order_id']) && $_SESSION['order_id'] == $oderid) {
        $response = array('status' => 1, 'msg' => '订单已经提交过了');
        echo json_encode($response);
        return;
    }

    $data_query = mysqli_query($con, "select * from oder where uid='$uid'");
    $count = mysqli_num_rows($data_query);

    if ($count > 10) {
        // 用户已经申请过了，返回状态码1和提示信息
        $response = array('status' => 1, 'msg' => '您申请的订单已超限，请联系客服');
        echo json_encode($response);
    } else {
        // 订单写入数据库成功后执行写入佣金表
        $data_insert = mysqli_query($con, "INSERT INTO oder(goods, name, uid, phone, sf, city, xian, dizhi, oderid, time, proxy_id, proxy_price, price ,api_type) VALUES ('$goods', '$name', '$uid', '$phone', '$sf', '$city', '$xian', '$dizhi', '$oderid', '$time', '$proxy_id', '$proxy_price', '$price' , '$api_type')");

        // 写入佣金表
        $data_revenue = mysqli_query($con, "INSERT INTO revenue(account, oderid, name, price, beizhu, cr_time) VALUES ('$proxy_acc', '$oderid', '$name', '$proxy_price', '$beizhu', '$time')");
    }
}
            $sql = "SELECT haokaid FROM list WHERE name='$goods'";
            $res = mysqli_query($con, $sql);
            if (mysqli_num_rows($res) > 0) {
                $row = mysqli_fetch_assoc($res);
                $haokaid = $row['haokaid'];
            }
            
            if ($haokaid == 0) {
                // haokaid等于0，直接输出申请成功
                $response = array('status' => 0, 'msg' => '申请成功');
                echo json_encode($response);
                // 将订单号写入session
                $_SESSION['order_id'] = $oderid;
                //发送短信通知
                sendSms($appId, $appKey, $phoneNumber, $templateId, $smsSign);
                exit;
            } else {
            $sql = "SELECT * FROM kefu";
            $res = mysqli_query($con, $sql);
            if (mysqli_num_rows($res) > 0) {
                $row = mysqli_fetch_assoc($res);
                $user_id = $row['appid'];
                $secret = $row['key'];
            }
            
            // 计算签名
            $user_sign = md5("Address=" . $dizhi . "&Area=" . $xian . "&City=" . $city . "&DownOrderID=" . $oderid . "&IDCard=" . $uid . "&Name=" . $name . "&Phone=" . $phone . "&ProductID=" . $haokaid . "&Province=" . $sf . "&ThirdPhone=&Timestamp=" . $time . "&user_id=" . $user_id . $secret);
            //   echo $user_sign;
            //   exit ;
            // 构造请求参数
            $params = array(
                'user_id' => $user_id,
                'Timestamp' => $time,
                'Name' => $name,
                'Phone' => $phone,
                'IDCard' => $uid,
                'Province' => $sf,
                'City' => $city,
                'Area' => $xian,
                'Address' => $dizhi,
                'ProductID' => $haokaid,
                'DownOrderID' => $oderid,
                'ThirdPhone' => '',
                'user_sign' => $user_sign,
            );

            // 构造请求头
            $headers = array(
                'Content-Type: application/x-www-form-urlencoded'
            );

            // 发送请求
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, 'https://haokaopenapi.lot-ml.com/api/order/ApiToOrder');
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $response = curl_exec($ch);
            curl_close($ch);

            // 解析响应数据
            $result = json_decode($response, true);
            if ($result['code'] == 0) {
                // 更新订单状态
                $update_sql = "UPDATE oder SET status=1, beizhu='$beizhus' WHERE oderid='$oderid'";
                $update_sql_revenue = "UPDATE revenue SET oder_sta=1 WHERE oderid='$oderid'";
                $update_query = mysqli_query($con, $update_sql);
    
                if ($update_query) {
                    // 更新成功，返回状态码0和提示信息
                    $response = array('status' => 0, 'msg' => '申请成功');
                    echo json_encode($response);
    
                    //发送短信通知
                    sendSms($appId, $appKey, $phoneNumber, $templateId, $smsSign);
                } else {
                    // 更新失败，返回状态码-2和提示信息
                    $response = array('status' => -2, 'msg' => '更新订单状态失败');
                    echo json_encode($response);
                }
            } else {
                // 下单失败，返回接口返回的错误信息
                $response = array('status' => $result['code'], 'msg' => $result['message']);
                echo json_encode($response);
            }
        }
}
